<script setup lang="ts">
import {
  getRoleDetailAPI,
  getRoleUserListAPI,
  getTreeListAPI,
} from "@/apis/system";
import type { RoleData, RoleParams } from "@/types/system";
import { User } from "@element-plus/icons-vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import type { TreeInstance } from "element-plus/lib/components/index.js";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const activeStep = ref(1);

const RoleForm = ref<RoleParams>({
  roleName: "",
  remark: "",
  perms: [],
});
const RoleRef = ref<FormInstance>();
const RoleRules = ref<FormRules<RoleParams>>({
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  remark: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
});
const treeList = ref<RoleData[]>([]); // 权限树形列表
// 获取功能权限列表
const getTreeList = async () => {
  const res = await getTreeListAPI();
  treeList.value = res.data;
};
getTreeList();
const treeRefs = ref<TreeInstance[]>([]);
const disTreeRefs = ref<TreeInstance[]>([]);
// 点击下一步
const activeNext = async () => {
  try {
    // 1. 校验表单
    if (activeStep.value === 1) {
      await RoleRef.value?.validate();
      activeStep.value++;
    } else if (activeStep.value === 2) {
        // 2. 获取树形组件的选中列表
        RoleForm.value.perms = []; // 清空数组,确保每次点击下一步时，数组为空
        treeRefs.value.forEach((tree) => {
          // 获取树形组件的选中节点
          const res = tree.getCheckedKeys();
          // 把每一个选中的节点，放入数组中
          RoleForm.value.perms.push(res as number[]);
        });
      // 通过判断，如果数组为空，则不提交数据
      if (RoleForm.value.perms.flat().length === 0) {
        ElMessage.error("请至少选择一项权限");
      } else {
        activeStep.value++;
        disTreeRefs.value.forEach((tree, index) => {
          tree.setCheckedKeys(RoleForm.value.perms[index]);
        });
      }
    }
  } catch {}
};
const router = useRouter();
const OnSubmit = async () => {
  await getRoleUserListAPI(RoleForm.value);
  ElMessage.success("添加成功");
  router.back();
};
const route = useRoute();
onMounted(async () => {
  if (route.params.id) {
    const res = await getRoleDetailAPI(route.params.id as string);
    RoleForm.value = res.data;
  }
});
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header
        v-if="$route.params.id"
        content="编辑角色"
        @back="$router.back()"
      />
      <el-page-header v-else content="添加角色" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" name="1" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div class="form-container" v-show="activeStep === 1">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form :model="RoleForm" :rules="RoleRules" ref="RoleRef">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                placeholder="请输入角色名称"
                v-model="RoleForm.roleName"
                style="width: 500px"
              />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input
                placeholder="请输入角色描述"
                v-model="RoleForm.remark"
                style="width: 500px"
                type="textarea"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container" v-show="activeStep === 2">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="treeRefs"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="{ label: 'title' }"
                :default-checked-keys="RoleForm.perms[index]"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="form-container" v-show="activeStep === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ RoleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ RoleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div
                v-for="(item, index) in treeList"
                :key="item.id"
                class="tree-item"
              >
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title', disabled: () => true }"
                  ref="disTreeRefs"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button
          v-show="activeStep > 1"
          @click="activeStep > 1 ? activeStep-- : (activeStep = 1)"
          >上一步</el-button
        >
        <el-button type="primary" v-if="activeStep < 3" @click="activeNext"
          >下一步</el-button
        >
        <el-button type="primary" v-else @click="OnSubmit">提交</el-button>
        {{ RoleForm }}
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;
    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }
    .right {
      text-align: right;
    }
  }
  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      margin-right: 300px;
      margin-left: 100px;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 200px;

        .el-form {
          display: block;
          // flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }
  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
